<?php
namespace App\Services;

use App\Services\ConfigService;
use App\Third\TLSSigAPIv2;
use Illuminate\Support\Facades\URL;

class ChatService extends BaseService
{
    public static function getUserSig($uid)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'], $config['private']);
        $userchat_config['identifier'] = 'dgg_' . $uid;

        $usersig = $sdk->genSig($userchat_config['identifier']);

        $userchat_config['usersig'] = $usersig;
        return $userchat_config;
    }

    /**
     * 批量导入账号
     * @param array $accounts
     * @return array
     * @throws
     */
    public static function importAccounts($accounts)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'], $config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/im_open_login_svc/multiaccount_import?sdkappid=' . $config['sdk_appid'] . '&identifier=' . $config['identifier'] . '&usersig=' . $usersig . '&random=99999999&contenttype=json';

        $data['Accounts'] = $accounts;

        $response = http_post($url, $data, 1);
        $result = json_decode($response, 1);
        return $result;
    }

    /**
     * 导入单账号
     * @param $param
     * @return mixed
     * @throws \Exception
     */
    public static function importAccount($param)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'], $config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=' . $config['sdk_appid'] . '&identifier=' . $config['identifier'] . '&usersig=' . $usersig . '&random=99999999&contenttype=json';

        $response = http_post($url, $param, 1);
        $result = json_decode($response, 1);
        return $result;
    }

    /**
     * 修改账户资料
     * @param $id
     * @param $param array nick:昵称 image：头像
     * @return mixed
     * @throws \Exception
     */
    public static function editAccount($id, $param)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'], $config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/profile/portrait_set?sdkappid=' . $config['sdk_appid'] . '&identifier=' . $config['identifier'] . '&usersig=' . $usersig . '&random=99999999&contenttype=json';

        $data = [
            "From_Account" => $id,
            "ProfileItem" =>[
                [
                    "Tag" => "Tag_Profile_IM_Nick",
                    "Value" => $param['nick']
                ],
                [
                    "Tag" => "Tag_Profile_IM_Image",
                    "Value" => isset($param['image'])?$param['image']:''
                ]
            ]
        ];
        $response = http_post($url, $data, 1);
        return json_decode($response, 1);
    }

    public static function getAccount($ids)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'], $config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/profile/portrait_get?sdkappid=' . $config['sdk_appid'] . '&identifier=' . $config['identifier'] . '&usersig=' . $usersig . '&random=99999999&contenttype=json';

        $data = [
            "To_Account" => $ids,
            "TagList" =>
            [
                "Tag_Profile_IM_Nick"
            ]
        ];
        $response = http_post($url, $data,  1);
        $result = json_decode($response, 1);

        return $result;
    }

    /**
     * 创建校派乐客服群
     * @param $uid string 客户
     * @param $groupName string 群名
     * @param $groupId string 群ID
     * @param $cs array 客服
     * @return string
     * @throws \Exception
     */
    public static function createXplChatRoom($uid, $groupName, $groupId, $cs)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'], $config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/create_group?sdkappid=' . $config['sdk_appid'] . '&identifier=' . $config['identifier'] . '&usersig=' . $usersig . '&random=99999999&contenttype=json';

        $memberList = [
            [
                "Member_Account"=> $uid, //客户
            ]
        ];

        foreach ($cs as $item){
            $memberList[] = [
                "Member_Account"=> $item, //客服
            ];
        }
        $data = [
            "Owner_Account" => "admin",
            "Type" => "ChatRoom",
            "GroupId"=> $groupId, // 用户自定义群组 ID（选填）
            "Name" => $groupName,
            "FaceUrl" =>  URL::asset('/static/wxapp/school/logo.png'),
            "MemberList" => $memberList
        ];

        $response = http_post($url, $data, 1);
        $result = json_decode($response, 1);
        return $result;
    }

    /**
     * 创建校派乐客服群
     * @param $uid string 客户
     * @param $groupName string 群名
     * @param $groupId string 群ID
     * @param $cs array 客服
     * @return string
     * @throws \Exception
     */
    public static function createXplWorkRoom($uid, $groupName, $groupId, $cs)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'], $config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/create_group?sdkappid=' . $config['sdk_appid'] . '&identifier=' . $config['identifier'] . '&usersig=' . $usersig . '&random=99999999&contenttype=json';

        $memberList = [
            [
                "Member_Account"=> $uid, //客户
            ]
        ];

        foreach ($cs as $item){
            $memberList[] = [
                "Member_Account"=> $item, //客服
            ];
        }
        $data = [
            "Owner_Account" => "admin",
            "Type" => "Private",
            "GroupId"=> $groupId, // 用户自定义群组 ID（选填）
            "Name" => $groupName,
            "FaceUrl" =>  URL::asset('/static/wxapp/school/logo.png'),
            "MemberList" => $memberList
        ];

        $response = http_post($url, $data, 1);
        $result = json_decode($response, 1);
        return $result;
    }

    /**
     * 静默添加成员
     * @param $groupId
     * @param $member
     */
    public static function addGroupMember($groupId, $member)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'],$config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/add_group_member?sdkappid='.$config['sdk_appid'].'&identifier='.$config['identifier'].'&usersig='.$usersig.'&random=99999999&contenttype=json';

        $memberList = [];
        foreach ($member as $item){
            $memberList[] = [
                "Member_Account"=> $item, //客服
            ];
        }

        $data = [
            "GroupId" => "$groupId",
            "MemberList" => $memberList,
            "Silence" => 1
        ];

        $response = http_post($url, $data, 1);
        return json_decode($response, 1);

    }

    /**
     * 静默删除成员
     * @param $groupId
     * @param $member
     */
    public static function delGroupMember($groupId, $member)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'],$config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/delete_group_member?sdkappid='.$config['sdk_appid'].'&identifier='.$config['identifier'].'&usersig='.$usersig.'&random=99999999&contenttype=json';

        $memberList = [];
        foreach ($member as $item){
            $memberList[] = $item; //客服
        }

        $data = [
            "GroupId" => "$groupId",
            "MemberToDel_Account" => $memberList,
            "Silence" => 1
        ];

        $response = http_post($url, $data, 1);
        return json_decode($response, 1);

    }

    /**
     * 发送群消息（自定义消息）
     * @param string $id from_account
     * @param $groupId
     * @param array $content
     * @return array
     * @throws
     */
    public static function sendGroupMsg($id, $groupId, $content)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'],$config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg?sdkappid='.$config['sdk_appid'].'&identifier='.$config['identifier'].'&usersig='.$usersig.'&random=99999999&contenttype=json';
        $data['From_Account'] = $id;
        $data['GroupId'] = $groupId;
        $data['Random'] = rand(100000,9999999);
        $data['MsgPriority'] = "COMMON";
        $data['MsgBody'][] = array(
            'MsgType'=>'TIMCustomElem',
            'MsgContent'=>$content,
        );
        $response = http_post($url,$data, 1);

        return json_decode($response, 1);
    }

    /**
     * 发送群消息（text消息）
     * @param string $id from_account
     * @param $groupId
     * @param array $content
     * @return array
     * @throws
     */
    public static function sendGroupTxtMessage($id, $groupId, $content)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'],$config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg?sdkappid='.$config['sdk_appid'].'&identifier='.$config['identifier'].'&usersig='.$usersig.'&random=99999999&contenttype=json';
        $data['From_Account'] = $id;
        $data['GroupId'] = $groupId;
        $data['Random'] = rand(100000,9999999);
        $data['MsgPriority'] = "COMMON";
        $data['MsgBody'][] = array(
            'MsgType'=>'TIMTextElem',
            'MsgContent'=>$content,
        );
        $response = http_post($url,$data, 1);

        return json_decode($response, 1);
    }

    /**
     * 解散群组
     * @param $groupId
     * @return mixed
     * @throws \Exception
     */
    public static function destroyGroup($groupId)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'],$config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/destroy_group?sdkappid='.$config['sdk_appid'].'&identifier='.$config['identifier'].'&usersig='.$usersig.'&random=99999999&contenttype=json';
        $data['GroupId'] = $groupId;

        $response = http_post($url,$data, 1);

        return json_decode($response, 1);
    }

    /**
     * 拉取群历史消息（默认10条）
     * @param $groupId
     * @param $num
     */
    public static function getGroupMessage($groupId, $num=10)
    {
        $config = ConfigService::getSysValueByType(3);
        $sdk = new TLSSigAPIv2($config['sdk_appid'],$config['private']);
        $usersig = $sdk->genSig($config['identifier']);
        $url = 'https://console.tim.qq.com/v4/group_open_http_svc/group_msg_get_simple?sdkappid='.$config['sdk_appid'].'&identifier='.$config['identifier'].'&usersig='.$usersig.'&random=99999999&contenttype=json';

        $data['GroupId'] = $groupId;
        $data['ReqMsgNumber'] = $num;

        $response = http_post($url,$data, 1);

        return json_decode($response, 1);
    }
}
